package com.hangzhou.welbeing.welbeinginstrument.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.AddCircleBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 09 月 14.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.activity
 * 工程名 welbeing_pregnant
 *
 * @desc 更换手机号
 */
public class ChangePhoneNumberActivity extends Activity {
    private static final String TAG = "ChangePhoneNumberActivity";
    @Bind(R.id.activity_change_phone_number_iv_return)
    ImageView activityChangePhoneNumberIvReturn;
    @Bind(R.id.activity_change_phone_number_et_phone_number)
    EditText activityChangePhoneNumberEtPhoneNumber;
    @Bind(R.id.activity_change_phone_number_et_password)
    EditText activityChangePhoneNumberEtPassword;
    @Bind(R.id.activity_change_phone_number_tv_forget_password)
    TextView activityChangePhoneNumberTvForgetPassword;
    @Bind(R.id.activity_change_phone_number_ll_input)
    LinearLayout activityChangePhoneNumberLlInput;
    @Bind(R.id.activity_change_phone_number_rl_login)
    RelativeLayout activityChangePhoneNumberRlLogin;

    private int i = RBConstants.COUNTDOWN;
    private Timer timer = null;
    private TimerTask task = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_phone_number);
        ButterKnife.bind(this);



        Utils.setStatusBar(this,false,false);
        Utils.setStatusTextColor(true,this);


    }

    @OnClick({R.id.activity_change_phone_number_iv_return, R.id.activity_change_phone_number_tv_forget_password, R.id.activity_change_phone_number_rl_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_change_phone_number_iv_return:
                finish();
                break;
            case R.id.activity_change_phone_number_tv_forget_password:
                String phoneNumber_01 =  activityChangePhoneNumberEtPhoneNumber.getText().toString().trim();
                if(!TextUtils.isEmpty(phoneNumber_01)){
                    countdown();
                    //获取验证码没做
                    getVersionCodeDate(phoneNumber_01);
                }else{
                    Toast.makeText(MyApplication.getMcontext(),"请输入手机号",Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.activity_change_phone_number_rl_login:
               String phoneNumber =  activityChangePhoneNumberEtPhoneNumber.getText().toString().trim();
                if(!TextUtils.isEmpty(phoneNumber)){
                    String versionCode = activityChangePhoneNumberEtPassword.getText().toString().trim();
                    if(!TextUtils.isEmpty(versionCode)){
                        loadChangePhoneNumber(phoneNumber,versionCode);
                    }else{
                        Toast.makeText(MyApplication.getMcontext(),"请输入验证码",Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(MyApplication.getMcontext(),"请输入手机号",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    /**
     * @DESC 获取验证码  Home/Customer/sendDuanxin
     * */
    private void getVersionCodeDate(String phoneNumber_01) {
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CHANGE_PHONE_NUMBER_VERSION_CODE)
                .addParams("tel", phoneNumber_01)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);


                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    /**
     * @desc  更换手机号
     * @param phoneNumber
     * @param versionCode*/
    private void loadChangePhoneNumber(String phoneNumber, String versionCode) {
        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CHANGE_PHONE_NUMBER)
                .addParams("cus_id", user_id)
                .addParams("tel", phoneNumber)
                .addParams("code", versionCode)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final AddCircleBean addCircleBean = gson.fromJson(praiseParseNetworkResponse,AddCircleBean.class);
                        if(addCircleBean.errorCode == 200 ){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),"手机号更改成功",Toast.LENGTH_SHORT).show();
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),addCircleBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }


    //倒计时
    private void countdown() {
        startTime();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (i > 0) {
                activityChangePhoneNumberTvForgetPassword.setText("重新发送" + i + "s");
                startTime();
            } else {
                stopTime();
                activityChangePhoneNumberTvForgetPassword.setText("获取验证码");
                i = 60;
            }
        }
    };
    public void startTime() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                i--;
                Message message = mHandler.obtainMessage();
                message.arg1 = i;
                mHandler.sendMessage(message);
            }
        };
        timer.schedule(task, 1000);
    }

    public void stopTime() {
        timer.cancel();
    }
}
